<?php
Yii::import('system.web.widgets.CWidget');

if (!function_exists('decode')) {
	function decode($enc) {
		$parts = imap_mime_header_decode($enc);
		$str='';
		for ($p=0; $p<count($parts); $p++) {
			$ch=$parts[$p]->charset;
			$part=$parts[$p]->text;
			if ($ch!=='default') $str .= mb_convert_encoding($part,'UTF-8',$ch);
			else $str.=$part;
		}
		return $str;
	}
}
	
class gmail extends CWidget {
	
    public function getMessages($username, $password) {
	
		//$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
		$hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}';
		$flag = "";
		$messages =  null;
		$inbox = imap_open($hostname,$username,$password,NULL,1) or die('Cannot connect to Gmail: ' . print_r(imap_errors()));
		$emails = imap_search($inbox,'ALL');
		
		if($emails) {
			$output = '';
			rsort($emails);

			foreach($emails as $email_number) {
				$overview = imap_fetch_overview($inbox,$email_number,0);
				//$seen = $overview[0]->seen ? 'read' : 'unread';
				$from = imap_utf8($overview[0]->from) . "<br/>";
				
				//if ($seen == "unread") {
					if (preg_match("/Календарь Google/i", $from)) {
						$subject = decode($overview[0]->subject);
						
						if (preg_match("/Напоминание/i", $subject)) {
							$flag = "1";
							$mDel[] = $email_number;
							$message = imap_fetchbody($inbox,$email_number,2);
							$message = iconv('KOI8-R', 'UTF-8', quoted_printable_decode($message));
							$message = preg_replace('/<p(.*)\/p>/iUs', '', $message);
							$messages .= preg_replace('/<a(.*)\/a>/iUs', '', $message) . "<br/>";
						}
					}
					/*else if (preg_match("/Denis Tutin/i", $from)) { 
						$subject = decode($overview[0]->subject);
						if (preg_match("/Приглашение/i", $subject)) {
							$message2 = imap_fetchbody($inbox,$email_number,1.2);
							$message2 = iconv('KOI8-R', 'UTF-8', quoted_printable_decode($message2));
							$message2 = preg_replace('/<p(.*)\/p>/iUs', '', $message2);
							$messages2 .= preg_replace('/<a(.*)\/a>/iUs', '', $message2) . "<br/>";
						}
					}*/
				//}
			}
			if ($flag == "1") {
				$flag = "";
				$this->render('view', array('msg' => $messages));
				/*foreach ($mDel as $m) {
					imap_delete($inbox,$m);
				}*/
			}
			else {
				return "Fail";
			}
			/*else if ($flagI == "1") {
				$flagI = "";
				$this->render('viewi', array('msg' => $messages2));
			}*/
		}
		else {
			return "Fail";
		}		
		imap_close($inbox);
	}
}
?>